/** axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios'
import router from '@/router/index.js'
import { message } from 'ant-design-vue'
import JSONBIG from 'json-bigint'

axios.defaults.transformResponse = [
  function (data) {
    const json = JSONBIG({
      storeAsString: true
    })
    const res = json.parse(data)
    return res
  }
]
console.log(import.meta.env.VITE_APP_BASE_API)
const baseURL = import.meta.env.VITE_APP_BASE_API
const instance = axios.create({
  baseURL: baseURL,
  timeout: 10000 * 30
  // withCredentials: true // 携带cookie
})

instance.interceptors.request.use(
  // 请求拦截
  async (config) => {
    config.headers['Authorization'] = localStorage.getItem('token')
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (!response.data.code) {
      return response
    }
    const res = response.data
    switch (res.code) {
      case 200: {
        return res
      }
      case '200': {
        return res
      }
      case '操作数据成功!id:': {
        return res
      }
      case '403': {
        message.error({
          content: res.desc || 'Error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(res.desc || 'Error'))
      }
      case 403: {
        message.error({
          content: res.desc || 'Error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(res.desc || 'Error'))
      }
      case 500: {
        message.error({
          content: res.desc || 'Error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(res.desc || 'Error'))
      }
      case '0204': {
        localStorage.setItem('token', '')
        router.push('/login')
        return Promise.reject(new Error(res.desc || 'Error'))
      }
      case '401001': {
        localStorage.setItem('token', '')
        router.push('/login')
        return Promise.reject(new Error(res.desc || 'Error'))
      }
    }
  },
  // 服务器状态码不是200的情况
  (error) => {
    if (error.code == 'ECONNABORTED') {
      localStorage.setItem('token', '')
      router.push('/login')
      return
    }
    if (error.response.status) {
      switch (error.response.status) {
        case 401:
        case 403:
          localStorage.setItem('token', '')
          router.push('/login')
          break
        // 404请求不存在
        case 404:
          break
        // 其他错误，直接抛出错误提示
        default:
          message.error({
            content: '您的网络卡顿，请刷新',
            duration: 5 * 1000
          })
      }
      return Promise.reject(error.response)
    } else {
      localStorage.setItem('token', '')
      router.push('/login')
    }
  }
)
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const $get = (url: string, params: object, extraPrarms: object | undefined) => {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: params,
        ...extraPrarms
      })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const $post = (url: string, params: object, extraPrarms: object | undefined) => {
  return new Promise((resolve, reject) => {
    instance
      .post(url, params, extraPrarms) // 是将对象 序列化成URL的形式，以&进行拼接
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

export default instance
export { $get, $post, axios }
